# @Time : 2024-09-27 15:22
# @Author : Fioman 
# @Phone : 13149920693
"""
生产日志类,生产过程中产生的日志都是这里来记录,日志一份输出到控制台,一份输出到日志文件.
也设置为单例类模式
"""
import logging
import os
import threading

from app_config import project_name, debug_dir
from common.datetime_helper import get_datetime_for_logger_dir


class ProduceLogger(object):
    """
    生产日志工具类
    """
    __instance = None
    __init_flag = False
    __lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            with cls.__lock:
                cls.__instance = super(ProduceLogger, cls).__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        if not self.__init_flag:
            print("ProduceLogger.__init__() 进行初始化")
            self.__init_flag = True
            self.file_debug = self.log_init().debug

    def debug(self, message):
        """
        封装一下debug,让其可以输出到控制台,然后在输出到日志文件目录
        :param message:
        :return:
        """
        print(message)
        self.file_debug(message)

    @staticmethod
    def remove_overdue_log():
        """
        删除过期的日志,目前默认过期时间为一个月,就是会删除掉上个月份的同样名字的日志.
        :return:
        """
        now_time = get_datetime_for_logger_dir()
        try:
            for root, _, filenames in os.walk(debug_dir):
                for filename in filenames:
                    day = filename[8:10]
                    month = filename[5:7]
                    now_day = now_time[8:10]
                    now_month = now_time[5:7]
                    if now_day == day and now_month != month:
                        os.remove(os.path.join(debug_dir, filename))
        except Exception as e:
            print(" error: {}".format(str(e)))

    def log_init(self):
        """
        初始化日志模块,要判断日志的目录是否存在,并且删除掉上一个月同一天的文件.
        :return:
        """
        # 删除过期日志
        self.remove_overdue_log()
        logger = logging.getLogger(__name__)
        logger.setLevel(level=logging.DEBUG)
        logger_file = f'{os.path.join(debug_dir, get_datetime_for_logger_dir())}_{project_name}_debug.txt'
        handler_ = logging.FileHandler(logger_file, encoding="UTF-8")
        handler_.setLevel(logging.DEBUG)
        formatter_ = logging.Formatter("%(asctime)s - %(message)s")
        handler_.setFormatter(formatter_)
        logger.addHandler(handler_)
        return logger


if __name__ == '__main__':
    logger1 = ProduceLogger()
    logger1.debug("我是一个测试Debug2")
    logger2 = ProduceLogger()
    logger2.debug("我是一个测试Debug2")
    logger3 = ProduceLogger()
    logger3.debug("我是一个测试Debug2")
    print(logger1 is logger2)
    print(logger2 is logger3)
